from flask import Blueprint, make_response, jsonify, request, redirect
from application.tools.captcha.captcha import captcha
from application.tools.myredis import r
from application.tools.myjwt import jwt
from application.tools.comm import sendMsg
import json, random, time, functools,requests
from application.models.users.user import *

user_blue = Blueprint("userblue", __name__, url_prefix="/user")


# def islogin(func):
#     @functools.wraps(func)
#     def wrapper():
#         func()
#         return func()
#     return wrapper

def islogin(type):
    def pemistion(func):
        @functools.wraps(func)
        def wrapper():
            func()
            if type == 1:
                return redirect("http://www.baidu.com")
            else:
                return redirect("http://www.jd.com")
        return wrapper
    return pemistion


# 获取图片验证码
@user_blue.route("/getcode")
def getcode():
    # 生成图片验证码
    name, text, image = captcha.generate_captcha()
    # 从页面获取uuid作为redis key
    uuid = str(request.args.get('uuid'))
    # 存入redis
    r.str_add(uuid, str(text), 60)
    # 以流的方式生成图形验证码
    res = make_response(image)
    res.headers['Content-Type'] = 'image/jpg'
    return res


@user_blue.route("/sendSmsCode", methods=['POST'])
def sendSmsCode():
    data = request.data
    if data:
        data = json.loads(data)
        uuid = data['uuid']
        piccode = data['piccode']
        mobile = data['mobile']
        value = r.str_get(uuid)
        if value:
            if piccode.lower() == value.lower():
                mcode = r.str_get(mobile)
                if mcode:
                    return jsonify({"code": 10012, "mes": '一分钟内不能重复发'})
                scode = random.randint(10000, 99999)
                print(scode)
                flag = sendMsg(mobile, scode)
                if flag == True:
                    r.str_add(mobile, scode, 60)
                    r.del_str(uuid)
                    return jsonify({"code": 200, 'mes': '发送成功'})
                else:
                    return jsonify({"code": 200, 'mes': '发送验证码失败'})
            else:
                return jsonify({"code": 10011, 'mes': '图片验证码错误'})
        else:
            return jsonify({"code": 10010, 'mes': '图片验证码不存在'})


@user_blue.route("/login", methods=['POST'])
def login():
    data = request.data
    if data:
        data = json.loads(data)
        mcode = data['code']
        mobile = data['mobile']
        code = r.str_get(mobile)
        if code:
            if int(code) == int(mcode):
                user = User.query.filter(User.mobile == mobile).first()
                if user:
                    r.del_str(mobile)
                else:
                    u = User(mobile=mobile, nikename=mobile)
                    db.session.add(u)
                    db.session.commit()
                    user = User.query.filter(User.mobile == mobile).first()
                    token = mjwt.jwt_encdoe(data={"data":{'uid':user.id,'exp':int(time.time())}})
                return jsonify({"code":200, 'token':token, 'userid':user.id})
            else:
                return jsonify({"code":10021, 'mes':'验证码错误'})
        else:
            return jsonify({"code":10020, 'mes':''})

# 获取weibo地址
@user_blue.route("/getwburl")
def getwburl():
    client_id="3674019597"
    redirect_uri="http://127.0.0.1:8000/user/weiboCallback/"
    url = "https://api.weibo.com/oauth2/authorize?client_id=%s&response_type=code&redirect_uri=%s"%(client_id,redirect_uri)
    return jsonify({"code":200,"url":url})

# weibo回调接口
@user_blue.route("/weiboCallback/")
def weiboCallback():
    # 获取code
    code = request.args.get('code')
    # 向access_token接口发起post请求
    data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
            "grant_type": "authorization_code",
            'redirect_uri': "http://127.0.0.1:8000/user/weiboCallback/", 'code': code}
    res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
    print(res.text)
    # 解析参数，token,uuid
    mes = json.loads(res.text)
    token = mes['access_token']
    uid = mes['uid']
    # 查询三方登陆中uid是否存在，如果存在，查询用户表，用用户信息生成token跳转到vue页面
    sql = "select user.id from user inner join sf_login on user.id=sf_login.userid where sf_login.uid='%s'" % (uid)
    user = db.session.execute(sql)
    # 判断是否查询到
    if user:
        for i in user:
            data = {"data": {"user.id": i[0], "exp": int(time.time())}}
            # token = mjwt.jwt_encode(data)
            token = mjwt.jwt_encode(data)
            return redirect("http://localhost:8080/#/updateToken?userid=" + str(i[0]) + "&token=" + token)

    # 不存在跳转到vue绑定页面，token uuid传递过去
    return redirect('http://localhost:8080/#/bindMobile?uid=' + uid + "&token=" + token)


# 绑定手机号
@user_blue.route("/bindMobile", methods=['POST'])
def bindMobile():
    data = json.loads(request.data)
    mobile = data['mobile']
    uid = data['uid']
    token = data['token']
    # 先查询用户表，如果手机号存在
    user = User.query.filter(User.mobile == mobile).first()
    if not user:
        # 添加用户
        u = User(mobile=mobile, nikename=mobile)
        db.session.add(u)
        db.session.commit()
        # 获取用户信息
        user = User.query.filter(User.mobile == mobile).first()

    sfuser = SfLogin(userid=user.id, webfrom='wb', uid=uid, token=token)
    db.session.add(sfuser)
    db.session.commit()
    # 如果不存在，写入user表
    # 获取userid，写入三方登录表，生成token返回
    data = {"data": user.id, "exp": int(time.time())}
    token = mjwt.jwt_encode(data)
    return jsonify({"userid": str(user.id), 'token': token})


# 购买vip生成订单
@user_blue.route("/buy",methods=['POST'])
def buy():
    # 获取参数
    data = json.loads(request.data)
    userid = data['userid']
    year = data['year']
    money = 200
    tmoney = money * int(year)
    order_no = str(time.time())+str(userid)+str(random.randint(100,999))
    viprecord = VipRecord(order_no=order_no,userid=userid,year=year,money=tmoney,active_money=tmoney,status=1)
    db.session.add(viprecord)
    db.session.commit()
    # 支付，返回支付url
    pay = get_ali_object()
         # 生成支付的url
    query_params = pay.direct_pay(
        subject="test",  # 商品简单描述
        out_trade_no=str(order_no),  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(1.00),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({"code":200,'url':pay_url})


import pymysql
from application.tools.comm import get_ali_object
@user_blue.route("/test")
def test():
    orderno = '234234'
    pay = get_ali_object()
         # 生成支付的url
    query_params = pay.direct_pay(
        subject="test",  # 商品简单描述
        out_trade_no=str(orderno),  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(1000.00),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({"code":200,'url':pay_url})